//
//  ListBar.m
//  FlyGift
//
//  Created by lanou3g on 15/7/16.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//


#import "ListBar.h"
#define itemFont 13  //字体的大小
#define kDistanceBetweenItem 32 // 两个ITem之间的距离大小
#define kExtraPadding 20
#define kScreenW [UIScreen mainScreen].bounds.size.width

/**
 *  控制展示首页的button的界面 以及一些操作
 */


@interface ListBar ()

@property(nonatomic, strong)NSMutableArray *btnLists;  // button的数组

@property(nonatomic, strong)UIView *btnBackView; // 跟随button的红色背景

@property(nonatomic, strong)UIButton *btnSeclect; // 记录被点击选择的button

@property(nonatomic, assign)CGFloat maxWidth;
@end

@implementation ListBar


#pragma mark - 懒加载 存放按钮的数组
- (NSMutableArray *)btnLists
{
    if (!_btnLists)
    {
        _btnLists = [NSMutableArray array];
    }
    return _btnLists;
}


#pragma mark - visibleItemList 重写setter方法
- (void)setVisibleItemList:(NSMutableArray *)visibleItemList
{
    _visibleItemList = visibleItemList;
    
    
    if (!self.btnBackView)
    {
        // 设置背景色 self代表的是scrollView
        self.btnBackView = [[UIView alloc]initWithFrame:CGRectMake(10, (self.frame.size.height - 20) / 2, 46, 20)];
        
        self.btnBackView.backgroundColor = kMainColor;
        
        self.btnBackView.layer.cornerRadius = 5;
        
        [self addSubview:_btnBackView];
        
        self.maxWidth = 20;
        
        self.backgroundColor = KColor(238, 238, 238, 1);
        
        // contentInset内容视图的上下左右四个边扩展出去的大小 默认是UIEdgeInsetsZero 也就是说没有扩展的边 right调为50
        self.contentInset = UIEdgeInsetsMake(0, 0, 0, 50);
        
        self.showsHorizontalScrollIndicator = NO;
        
        for (int i = 0; i < visibleItemList.count; i++)
        {
            [self makeItemWithTitle:visibleItemList[i]];
        }
        
        self.contentSize = CGSizeMake(self.maxWidth, self.frame.size.height);
    }
}


#pragma mark - 每个Item就是一个button按钮
// 根据标题
- (void)makeItemWithTitle:(NSString *)title
{
    // 每个Item的宽度
    CGFloat itemW = [self calculateSizeWithFont:itemFont Text:title].size.width;
    
    // 根据得到的宽度 设置button的属性
    UIButton *itemButton = [[UIButton alloc]initWithFrame:CGRectMake(self.maxWidth, 0, itemW, self.frame.size.height)];
    
    itemButton.titleLabel.font = [UIFont systemFontOfSize:itemFont];
    
    [itemButton setTitle:title forState:UIControlStateNormal];
    
    [itemButton setTitleColor:kMainColor forState:UIControlStateNormal];
    
    [itemButton setTitleColor:kMainColor forState:UIControlStateHighlighted];
    
    [itemButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    // 添加事件
    [itemButton addTarget:self action:@selector(ItemButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 按钮的宽度+两个按钮之间的间距
    self.maxWidth += itemW + kDistanceBetweenItem;
    
    [self.btnLists addObject:itemButton];
    
    [self addSubview:itemButton];
    
    if (!self.btnSeclect)
    {
        [itemButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.btnSeclect = itemButton;
    }
    self.contentSize = CGSizeMake(self.maxWidth, self.frame.size.height);

    
}

/**
 *  选中状态下按钮 是红色的 没有选中的都是白色的
 *
 */
- (void)ItemButtonAction:(UIButton *)sender
{
    // 如果点击的按钮不是选中的按钮
    if (self.btnSeclect != sender)
    {
        // 那么设置选中的按钮的颜色为红色
        [self.btnSeclect setTitleColor:kMainColor forState:UIControlStateNormal];
        // 将没有选中的按钮的颜色为白色
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        // 点击这个按钮之后  更新被选中的这个按钮
        self.btnSeclect = sender;
        
        if (self.listBarItemClickBlock)
        {
            // 得到button的标题
            NSString *itemName = sender.titleLabel.text;
            // 然后根据button的标题找到其在数组中的下标
            NSInteger itemIndex = [self findIndexOfListsWithTitile:itemName];
            
            // 发送指令 去执行block块中的方法
            self.listBarItemClickBlock(itemName,itemIndex);
        }
        
        // 设置动画的速度效果 渐入渐出（EaseInOut）
        [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            // 得到按钮背景的frame
            CGRect btnBackViewRect = self.btnBackView.frame;
            
            CGFloat changeW = sender.frame.origin.x - (btnBackViewRect.size.width - sender.frame.size.width) / 2 - 10;
            
            // .CGAffineTransformMakeTranslation每次都是以最初位置的中心点为起始参照 点击一次button移动一下
            self.btnBackView.transform = CGAffineTransformMakeTranslation(changeW, 0);
            
        } completion:^(BOOL finished) {
            //当移动backView动画完成时
            // 判断
            [UIView animateWithDuration:0.3 animations:^{
               
                CGPoint changePoint;
                if (sender.frame.origin.x >= kScreenW - 150 && sender.frame.origin.x < self.contentSize.width - 200)
                {
                    changePoint = CGPointMake(sender.frame.origin.x - 200, 0);
                }
                else if (sender.frame.origin.x >= self.contentSize.width - 200)
                {
                    changePoint = CGPointMake(self.contentSize.width - 350, 0);
                }
                else
                {
                    changePoint = CGPointMake(0, 0);
                }
                
                self.contentOffset = changePoint;
            }];
            
        }];
        
    }
}


#pragma mark - 计算字符串的大小 自适应
// 根据传进来的字体的大小和字符串中的内容计算size大小
- (CGRect)calculateSizeWithFont:(NSInteger)font Text:(NSString *)text
{
//    NSDictionary *attr = @{NSFontAttributeName : [UIFont systemFontOfSize:font]};
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, self.frame.size.height)
                                     options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                  attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:font] forKey:NSFontAttributeName]
                                     context:nil];
    return rect;
}


#pragma mark - 根据Item(即button)的title找到其在数组中对应的下标
- (NSInteger)findIndexOfListsWithTitile:(NSString *)title

{
    for (int i = 0; i < self.visibleItemList.count; i++)
    {
        if ([title isEqualToString:self.visibleItemList[i]])
        {
            return i;
        }
    }
    return 0;
}


#pragma mark - 根据标题找到button并删除
- (void)removeItemWithTitle:(NSString *)title
{
    NSInteger index = [self findIndexOfListsWithTitile:title];
    
    UIButton *selectButtonTemp = self.btnLists[index];
    
    [self.btnLists[index] removeFromSuperview];
    
    [self.btnLists removeObject:selectButtonTemp];
    
    [self.visibleItemList removeObject:title];
}


#pragma mark - 滑动到某一个下标处点击了按钮
- (void)itemClickByScrollerWithIndex:(NSInteger)index
{
    UIButton *itemButton = (UIButton*)self.btnLists[index];
    [self ItemButtonAction:itemButton];
}



/**
 *  typedef enum{
 topViewClick = 0,
 FromTopToTop = 1,
 FromTopToTopLast = 2,
 FromTopToBottomHead = 3,
 FromBottomToTopLast = 4
 } animateType;
 */

- (void)operationFromBlock:(animateType)type item:(NSString *)itemName index:(int)index
{
    switch (type)
    {
        case topViewClick:
        {
            NSInteger tempIndex =  [self findIndexOfListsWithTitile:itemName];
            UIButton *button = self.btnLists[tempIndex];
            [self ItemButtonAction:button];
            
            if (self.arrowChange)
            {
                self.arrowChange();
            }
        }
            
            break;
        case FromTopToTop:
            
            [self switchPositionWithItemName:itemName index:index];
            
            break;
        case FromTopToTopLast:
            [self switchPositionWithItemName:itemName index:self.visibleItemList.count - 1];
            
            break;
        case FromTopToBottomHead: // 如果被选择的button跟操作的相等的话
            
            if ([self.btnSeclect.titleLabel.text isEqualToString:itemName])
            {
                [self ItemButtonAction:self.btnLists[0]];
            }
            [self removeItemWithTitle:itemName];
            [self resetFrame];
            
            break;
        case FromBottomToTopLast:
            [self.visibleItemList addObject:itemName];
            [self makeItemWithTitle:itemName];
            break;
            
        default:
            break;
    }
}



// 根据标题以及下标 选择被选择的位置
- (void)switchPositionWithItemName:(NSString *)itemName index:(NSInteger)index
{
    UIButton *button = self.btnLists[[self findIndexOfListsWithTitile:itemName]];
    
    [self.visibleItemList removeObject:itemName]; // 移除名字
    
    [self.btnLists removeObject:button]; //移除按钮
    
    [self.visibleItemList insertObject:itemName atIndex:index]; // 在下标出插入
    
    [self.btnLists insertObject:button atIndex:index];
    
    [self ItemButtonAction:self.btnSeclect];
    
    [self resetFrame];
}



#pragma mark - 重置frame

- (void)resetFrame
{
    self.maxWidth = 20;
    for (int i = 0; i < self.visibleItemList.count; i++)
    {
        [UIView animateWithDuration:0.001 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
            
            // 先计算每个Item的宽度
            CGFloat itemW = [self calculateSizeWithFont:itemFont Text:self.visibleItemList[i]].size.width;
            
            // 然后设置button的frame
            [[self.btnLists objectAtIndex:i] setFrame:CGRectMake(self.maxWidth, 0, itemW, self.frame.size.height)];
            
            self.maxWidth += kDistanceBetweenItem + itemW;
            
        } completion:nil];
    }
    
    // 计算scorllView的容量大小
    self.contentSize = CGSizeMake(self.maxWidth, self.frame.size.height);
}
@end





















